const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')

const app = express()
const PORT = 3001

// 中间件
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))

// 模拟用户数据
const users = [
  { id: 1, username: 'admin', password: '123456' },
  { id: 2, username: 'user', password: '123456' },
  { id: 3, username: 'test', password: '123456' }
]

// 登录接口
app.post('/api/login', (req, res) => {
  const { username, password } = req.body
  
  // 简单验证
  if (!username || !password) {
    return res.json({
      success: false,
      message: '用户名和密码不能为空'
    })
  }
  
  // 查找用户
  const user = users.find(u => u.username === username && u.password === password)
  
  if (user) {
    // 生成简单token
    const token = Buffer.from(`${user.id}:${user.username}`).toString('base64')
    
    res.json({
      success: true,
      message: '登录成功',
      token,
      user: {
        id: user.id,
        username: user.username
      }
    })
  } else {
    res.json({
      success: false,
      message: '用户名或密码错误'
    })
  }
})

// 验证token接口
app.get('/api/verify', (req, res) => {
  const token = req.headers.authorization?.split(' ')[1]
  
  if (!token) {
    return res.json({ success: false, message: '未提供token' })
  }
  
  try {
    const decoded = Buffer.from(token, 'base64').toString()
    const [id, username] = decoded.split(':')
    
    const user = users.find(u => u.id === parseInt(id) && u.username === username)
    
    if (user) {
      res.json({ success: true, user: { id: user.id, username: user.username } })
    } else {
      res.json({ success: false, message: 'token无效' })
    }
  } catch (error) {
    res.json({ success: false, message: 'token格式错误' })
  }
})

// 健康检查接口
app.get('/api/health', (req, res) => {
  res.json({ status: 'ok', message: '服务器运行正常' })
})

// 启动服务器
app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`)
  console.log('可用测试账号:')
  console.log('- 用户名: admin, 密码: 123456')
  console.log('- 用户名: user, 密码: 123456')
  console.log('- 用户名: test, 密码: 123456')
})